package org.ehe.ai.controller;


import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.ehe.ai.domain.ChatMessage;
import org.ehe.ai.domain.ChatSession;
import org.ehe.ai.domain.dto.ChatRequest;
import org.ehe.ai.domain.dto.ChatResponse;
import org.ehe.ai.service.ChatService;
import org.ehe.ai.service.StreamChatService;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author :zhangnn
 * @className :ChatController
 * @description: TODO
 * @date 2025-08-23 09:27:26
 */
@Slf4j
@RestController
@RequestMapping("/chat")
@CrossOrigin(origins = "*") // 允许跨域，生产环境建议配置具体域名
public class ChatController {

    @Autowired
    private ChatService chatService;
    @Autowired
    private StreamChatService streamChatService;

    /**
     * 创建新的聊天会话
     * @param userId
     * @return
     */
    @PostMapping("/session/create")
    public R<Map<String, Object>> createSession(@RequestParam(required = false) String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            String sessionId = chatService.createSession(userId,null);
            result.put("success", true);
            result.put("sessionId", sessionId);
            result.put("message", "会话创建成功");
            return R.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "会话创建失败: " + e.getMessage());
            return R.fail(result);
        }
    }

    /**
     * 发送消息
     * @param request
     * @param httpRequest
     * @return
     */
    @PostMapping("/message/send")
    public R<ChatResponse> sendMessage(@RequestBody ChatRequest request, HttpServletRequest httpRequest) {
        ChatResponse response = chatService.sendMessage(request, httpRequest);

        if (response.isSuccess()) {
            return R.ok(response);
        } else {
            return R.fail(response);
        }
    }

    /**
     * 获取会话历史消息
     * @param sessionId
     * @return
     */
    @GetMapping("/session/{sessionId}/messages")
    public R<Map<String, Object>> getSessionMessages(@PathVariable String sessionId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ChatMessage> messages = chatService.getSessionMessages(sessionId);
            result.put("success", true);
            result.put("messages", messages);
            return R.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取消息失败: " + e.getMessage());
            return R.fail(result);
        }
    }

    /**
     * 获取用户的会话列表
     * @param userId
     * @return
     */
    @GetMapping("/sessions")
    public R<Map<String, Object>> getUserSessions(@RequestParam(required = false) String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if(StringUtils.isBlank(userId)){
                userId = String.valueOf(LoginHelper.getUserId());
            }
            List<ChatSession> sessions = chatService.getUserSessions(userId);
            result.put("success", true);
            result.put("sessions", sessions);
            return R.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取会话列表失败: " + e.getMessage());
            return R.fail(result);
        }
    }

    /**
     * 删除会话
     * @param sessionId
     * @param userId
     * @return
     */
    @DeleteMapping("/session/{sessionId}")
    public R<Map<String, Object>> deleteSession(@PathVariable("sessionId") String sessionId,
                                                @RequestParam(required = false) String userId) {
        Map<String, Object> result = new HashMap<>();
        chatService.deleteSession(sessionId,userId);
        result.put("success", true);
        result.put("message", "会话删除成功");
        return R.ok(result);
    }

    // ==================== 流式聊天相关接口 ====================/

    /**
     * 流式聊天（Server-Sent Events）
     */
    @GetMapping(value = "/stream/connect/{sessionId}", produces = "text/event-stream")
    public SseEmitter connectStream(@PathVariable String sessionId) {
        log.info("[AI]创建SSE连接，会话ID: {}", sessionId);
        return streamChatService.createSseConnection(sessionId);
    }

    /**
     * 流式聊天
     * @param request
     * @return
     */
    @PostMapping("/stream/message")
    public R<Map<String, Object>> streamMessage(@RequestBody ChatRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证会话ID
            if (request.getSessionId() == null || request.getSessionId().isEmpty()) {
                result.put("success", false);
                result.put("message", "会话ID不能为空");
                return R.fail(result);
            }

            // 开始流式处理
            streamChatService.streamMessage(request);

            result.put("success", true);
            result.put("message", "开始处理消息");
            return R.ok(result);

        } catch (Exception e) {
            log.error("流式消息处理失败", e);
            result.put("success", false);
            result.put("message", "处理失败: " + e.getMessage());
            return R.fail(result);
        }
    }

    /**
     * 关闭SSE连接
     * @param sessionId
     * @return
     */
    @DeleteMapping("/stream/close/{sessionId}")
    public R<Map<String, Object>> closeStream(@PathVariable String sessionId) {
        Map<String, Object> result = new HashMap<>();

        streamChatService.closeSseConnection(sessionId);
        result.put("success", true);
        result.put("message", "连接已关闭");

        return R.ok(result);
    }

    /**
     * 获取连接状态
     * @return
     */
    @GetMapping("/stream/status")
    public R<Map<String, Object>> getStreamStatus() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("activeConnections", streamChatService.getActiveConnectionCount());
        return R.ok(result);
    }
}
